<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import FreightSelector from './FreightSelector.vue' // 引入子组件

const emit = defineEmits(['submit', 'close'])

const form = ref({
  waybillNo: '',
  carrier: '',
  departureCity: '',
  arrivalCity: ''
})

const visible = ref(false)
const freightSelectorRef = ref(null)

const open = () => {
  visible.value = true
}

const close = () => {
  visible.value = false
  resetForm()
}

const submit = () => {
  if (!form.value.waybillNo || !form.value.carrier) {
    ElMessage.error('请填写运单号和承运单位')
    return
  }
  emit('submit', form.value)
  close()
}

const resetForm = () => {
  form.value = {
    waybillNo: '',
    carrier: '',
    departureCity: '',
    arrivalCity: ''
  }
}

const openFreightSelector = () => {
  freightSelectorRef.value.open()
}

const handleFreightConfirm = (data) => {
  form.value.carrier = data.carrier
  form.value.departureCity = data.departureCity
  form.value.arrivalCity = data.arrivalCity
}

const handleClose = () => {
  close()
}

defineExpose({
  open,
  close
})
</script>

<template>
  <el-dialog
    title="设置承运单位"
    v-model="visible"
    width="500px"
    :before-close="handleClose"
  >
    <el-form :model="form" label-width="100px">
      <el-form-item label="运单号">
        <el-input v-model="form.waybillNo" placeholder="请输入运单号" />
      </el-form-item>
      <el-form-item label="承运单位">
        <el-input v-model="form.carrier" placeholder="请输入承运单位" />
      </el-form-item>
      <el-form-item label="始发城市">
        <el-input v-model="form.departureCity" placeholder="请输入始发城市" />
      </el-form-item>
      <el-form-item label="到货城市">
        <el-input v-model="form.arrivalCity" placeholder="请输入到货城市" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="openFreightSelector">选择承运商</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 弹出运费选择框 -->
  <FreightSelector ref="freightSelectorRef" @confirm="handleFreightConfirm" />
</template>

